package com.hospital.hospitalserver.service;

import com.hospital.hospitalserver.entity.*;
import com.hospital.hospitalserver.entity.Vo.ExamOrderItemVO;
import com.hospital.hospitalserver.entity.Vo.ExamOrderVO;
import com.hospital.hospitalserver.entity.Vo.PaymentItemVO;
import com.hospital.hospitalserver.entity.Vo.PaymentVO;
import com.hospital.hospitalserver.exception.CustomException;
import com.hospital.hospitalserver.mapper.ExamOrderMapper;
import com.hospital.hospitalserver.mapper.PaymentMapper;
import com.hospital.hospitalserver.util.PaymentItemReceiptGenerator;
import com.hospital.hospitalserver.util.Response;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 检查项目功能实现类
 * */
@Service
@RequiredArgsConstructor
public class ExamOrderService {
    private final ExamOrderMapper examOrderMapper;
    //收费管理
    private final PaymentMapper paymentMapper;
    private final MedicalInsuranceService medicalInsuranceService;

    /**
     * 医生工作台-诊断记录
     * 添加检查项目
     * 增加事务管理
     * */
    @Transactional
    public Response createExamOrder(ExamOrderRequest request){
        try {
            // 2. 检查是否已存在检查申请记录（查询所有订单）
            List<ExamOrderVO> existingOrders = examOrderMapper.selectExamOrderListByVisitId(request.getVisit_id());

            // 验证订单状态（基于所有订单）
            Response validationResponse = validateOrderForAddingItems(existingOrders);
            if (validationResponse.getCode() != 200) {
                return validationResponse;
            }

            String operationType = (String) validationResponse.getData();
            Integer orderId;

            if ("ADD_TO_EXISTING".equals(operationType)) {
                // 情况1：向现有待缴费订单添加项目
                // 找到可追加的待缴费订单
                ExamOrderVO existingOrder = existingOrders.stream()
                        .filter(order -> "pending".equals(order.getPayment_status())
                                && !"cancelled".equals(order.getOrder_status()))
                        .findFirst()
                        .orElseThrow(() -> new RuntimeException("未找到可追加的待缴费订单"));

                orderId = existingOrder.getOrder_id();

                // 验证订单状态是否允许添加（新增检查）
                if (!"created".equals(existingOrder.getOrder_status())) {
                    return Response.error("当前检查申请状态不允许添加新项目");
                }

                // 插入新的检查项目明细
                if (request.getOrder_items() != null && !request.getOrder_items().isEmpty()) {
                    int itemsResult = examOrderMapper.insertExamOrderItems(orderId, request.getOrder_items());
                    if (itemsResult <= 0) {
                        throw new RuntimeException("检查项目明细插入失败");
                    }
                }

                // 重新计算并更新总金额
                BigDecimal newTotal = examOrderMapper.calculateOrderTotalFee(orderId);
                examOrderMapper.updateOrderTotalFee(orderId, newTotal);

                // 更新收费记录
                updatePaymentRecord(existingOrder, request, newTotal);

            } else {
                // 情况2：不存在检查申请记录，创建新的检查申请（包括已缴费后新建）
                // 设置默认值
                setDefaultValues(request);

                // 如果是已缴费后新建，可以记录相关信息（可选）
                if ("CREATE_NEW_AFTER_PAID".equals(operationType)) {
                    // 可以在临床诊断或检查要求中备注
                    if (request.getExam_requirements() == null) {
                        request.setExam_requirements("在已缴费检查单后追加的新检查项目");
                    } else {
                        request.setExam_requirements(request.getExam_requirements() + "\n[在已缴费检查单后追加]");
                    }
                }

                // 如果是退款后新建
                if ("CREATE_NEW_AFTER_REFUND".equals(operationType)) {
                    if (request.getExam_requirements() == null) {
                        request.setExam_requirements("退款后重新开具的检查项目");
                    } else {
                        request.setExam_requirements(request.getExam_requirements() + "\n[退款后重新开具]");
                    }
                }

                // 插入检查申请主表
                int orderResult = examOrderMapper.insertExamOrder(request);
                if (orderResult <= 0) {
                    return Response.error("检查申请创建失败");
                }

                // 获取生成的订单ID
                orderId = request.getOrder_id();

                // 插入检查申请明细表
                if (request.getOrder_items() != null && !request.getOrder_items().isEmpty()) {
                    int itemsResult = examOrderMapper.insertExamOrderItems(orderId, request.getOrder_items());
                    if (itemsResult <= 0) {
                        throw new RuntimeException("检查项目明细插入失败");
                    }
                }

                // 创建收费表信息
                createPaymentRecord(request);
            }

            return Response.success("检查申请创建成功");

        } catch (Exception e) {
            return Response.error(e.toString());
        }
    }

    /**
     * 验证订单是否可以添加项目 - 基于实际表结构
     */
    private Response validateOrderForAddingItems(List<ExamOrderVO> existingOrders) {
        if (existingOrders == null || existingOrders.isEmpty()) {
            return Response.success("CREATE_NEW"); // 不存在订单，创建新单
        }

        // 检查是否有可用的待缴费订单（优先使用）
        Optional<ExamOrderVO> pendingOrder = existingOrders.stream()
                .filter(order -> "pending".equals(order.getPayment_status())
                        && !"cancelled".equals(order.getOrder_status()))
                .findFirst();

        if (pendingOrder.isPresent()) {
            ExamOrderVO order = pendingOrder.get();
            // 待缴费的订单可以追加项目
            return Response.success("ADD_TO_EXISTING");
        }

        // 检查所有订单的状态，找出最新的非取消订单作为参考
        Optional<ExamOrderVO> latestValidOrder = existingOrders.stream()
                .filter(order -> !"cancelled".equals(order.getOrder_status()))
                .max(Comparator.comparing(ExamOrderVO::getApply_time));

        if (!latestValidOrder.isPresent()) {
            // 所有订单都已取消，创建新单
            return Response.success("CREATE_NEW");
        }

        ExamOrderVO latestOrder = latestValidOrder.get();

        // 已取消的订单不允许添加项目
        if ("cancelled".equals(latestOrder.getOrder_status())) {
            return Response.error("已取消的检查申请不允许添加新项目");
        }

        // 关键修改：已缴费的订单创建新申请，而不是报错
        if ("paid".equals(latestOrder.getPayment_status())) {
            return Response.success("CREATE_NEW_AFTER_PAID");
        }

        // 待缴费的订单可以追加项目（理论上这里不会执行，因为前面已经检查过）
        if ("pending".equals(latestOrder.getPayment_status())) {
            return Response.success("ADD_TO_EXISTING");
        }

        // 已退款的订单创建新申请
        if ("refunded".equals(latestOrder.getPayment_status())) {
            return Response.success("CREATE_NEW_AFTER_REFUND");
        }

        return Response.error("未知的缴费状态: " + latestOrder.getPayment_status());
    }

    /**
     * 更新收费记录（向现有检查申请添加项目时使用）
     */
    private void updatePaymentRecord(ExamOrderVO existingOrder, ExamOrderRequest newRequest, BigDecimal newTotal) {
        try {
            // 获取报销比例
            Double reimbursementRate = medicalInsuranceService.getReimbursementRate(newRequest.getInsurance_card_number());

            // 计算医保支付金额
            Map<String, BigDecimal> paymentDetails = medicalInsuranceService.calculateInsurancePayment(newTotal,reimbursementRate);

            BigDecimal insurancePayment = paymentDetails.get("insurancePayment");
            BigDecimal personalPayment = paymentDetails.get("personalPayment");
            // 1. 获取现有的收费记录ID
            List<ExamOrderItemVO> existingItems = examOrderMapper.selectExamOrderItems(existingOrder.getOrder_id());
            if (existingItems.isEmpty() || existingItems.get(0).getPayment_id() == null) {
                throw new RuntimeException("未找到有效的收费记录");
            }

            Integer paymentId = existingItems.get(0).getPayment_id();

            // 2. 创建新的收费项目明细
            List<PaymentItemDTO> newPaymentItems = newRequest.getOrder_items().stream()
                    .map(item -> {
                        PaymentItemDTO paymentItem = new PaymentItemDTO();
                        paymentItem.setPayment_id(paymentId);
                        paymentItem.setFee_item_id(item.getFee_item_id());
                        paymentItem.setItem_name(item.getExam_name());
                        paymentItem.setUnit_price(item.getUnit_price());
                        paymentItem.setQuantity(item.getQuantity());
                        paymentItem.setAmount(item.getAmount());
                        paymentItem.setCategory_id(getCategoryIdByExamType(item.getExam_category()));
                        paymentItem.setCategory_name(getCategoryNameByExamType(item.getExam_category()));
                        paymentItem.setInsurance_type(item.getInsurance_type());
                        paymentItem.setDoctor_id(newRequest.getDoctor_id());
                        paymentItem.setDoctor_name(newRequest.getDoctor_name());
                        paymentItem.setDepartment_id(newRequest.getDepartment_id());
                        paymentItem.setDepartment_name(newRequest.getDepartment_name());
                        paymentItem.setCreate_time(LocalDateTime.now());
                        return paymentItem;
                    })
                    .collect(Collectors.toList());

            // 3. 插入新的收费项目
            int itemsResult = paymentMapper.insertPaymentItems(newPaymentItems);
            if (itemsResult <= 0) {
                throw new CustomException("收费项目明细插入失败");
            }

            // 4. 更新收费主表金额和医保信息
            paymentMapper.updatePaymentAmountAndInsurance(paymentId, newTotal,
                    newRequest.getInsurance_card_number(),
                    reimbursementRate != null ? reimbursementRate.toString() : "0",
                    insurancePayment, personalPayment);

            // 5. 更新检查项目明细的payment_id
            updateExamItemsPaymentId(existingOrder.getOrder_id(), paymentId);

        } catch (Exception e) {
            throw new CustomException("更新收费记录失败:" + e.getMessage());
        }
    }

    /**
     * 数据验证
     */
    private Response validateExamOrderRequest(ExamOrderRequest request) {
        if (request.getVisit_id() == null) {
            return Response.error("就诊记录ID不能为空");
        }

        // 验证就诊记录是否存在
        int visitExists = examOrderMapper.checkVisitExists(request.getVisit_id());
        if (visitExists == 0) {
            return Response.error("就诊记录不存在");
        }

        if (request.getOrder_items() == null || request.getOrder_items().isEmpty()) {
            return Response.error("检查项目不能为空");
        }

        // 验证费用项目是否存在
        for (ExamOrderItemDTO item : request.getOrder_items()) {
            if (item.getFee_item_id() == null) {
                return Response.error("费用项目ID不能为空");
            }
            int feeItemExists = examOrderMapper.checkFeeItemExists(item.getFee_item_id());
            if (feeItemExists == 0) {
                return Response.error("费用项目不存在：" + item.getExam_name());
            }
        }

        // 移除对总金额的严格验证，因为当向现有订单添加项目时，前端传入的 total_fee 只是新增项目的总金额
        // 总金额的计算和更新将在服务层处理

        return Response.success();
    }

    /**
     * 设置默认值
     */
    private void setDefaultValues(ExamOrderRequest request) {
        // 订单号已在实体类的 set 方法中生成
        if (request.getOrder_status() == null) {
            request.setOrder_status("created");
        }
        if (request.getPayment_status() == null) {
            request.setPayment_status("pending");
        }
        if (request.getApply_time() == null) {
            request.setApply_time(java.time.LocalDateTime.now());
        }

        // 设置项目默认状态
        if (request.getOrder_items() != null) {
            for (ExamOrderItemDTO item : request.getOrder_items()) {
                if (item.getItem_status() == null) {
                    item.setItem_status("pending");
                }
                if (item.getResult_status() == null) {
                    item.setResult_status("pending");
                }
            }
        }
    }

    /**
     * 医生工作台-诊断记录
     * 加载检查项目
     */
    public Response getExamOrderByVisitId(ExamOrderRequest request) {
        try {
            // 修改：查询所有订单，而不是单个订单
            List<ExamOrderVO> examOrders = examOrderMapper.selectExamOrderListByVisitId(request.getVisit_id());

            //这里加载可以为空
            if (examOrders == null || examOrders.isEmpty()) {
                // 返回空对象
                ExamOrderVO emptyOrder = new ExamOrderVO();
                emptyOrder.setVisit_id(request.getVisit_id());
                emptyOrder.setOrder_items(new ArrayList<>());
                return Response.success(emptyOrder);
            }

            // 合并所有订单的项目
            List<ExamOrderItemVO> allItems = new ArrayList<>();
            for (ExamOrderVO order : examOrders) {
                List<ExamOrderItemVO> items = examOrderMapper.selectExamOrderItems(order.getOrder_id());
                if (items != null) {
                    allItems.addAll(items);
                }
            }

            // 创建一个合并的订单对象返回给前端
            ExamOrderVO resultOrder = examOrders.get(0); // 使用第一个订单作为基础
            resultOrder.setOrder_items(allItems);

            // 计算总费用（所有订单的总和）
            BigDecimal totalFee = allItems.stream()
                    .map(item -> item.getAmount() != null ? item.getAmount() : BigDecimal.ZERO)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            resultOrder.setTotal_fee(totalFee);

            return Response.success(resultOrder);
        } catch (Exception e) {
            return Response.error("查询检查申请失败");
        }
    }

    /**
     * 医生工作台-诊断记录
     * 删除检查项目（支持删除整个订单或单个子项）
     * 如果删除后订单没有子项了，自动删除整个订单
     */
    @Transactional
    public Response deleteExamOrderItem(ExamOrderRequest request) {
        Integer orderId = request.getOrder_id();
        Integer itemId = request.getItem_id();
        String insurance_card_number = request.getInsurance_card_number();
        try {
            // 1. 检查订单状态
            ExamOrderRequest order = examOrderMapper.selectExamOrderById(orderId);
            if (order == null) {
                return Response.error("检查申请不存在");
            }

            // 只有特定状态可以删除
            if (!"created".equals(order.getOrder_status()) || !"pending".equals(order.getPayment_status())) {
                return Response.error("当前状态不允许删除检查项目");
            }

            // 2. 获取要删除的项目信息（用于更新收费表）
            ExamOrderItemDTO deletedItem = examOrderMapper.selectExamOrderItemById(itemId);
            if (deletedItem == null) {
                return Response.error("检查项目不存在");
            }

            // 3. 删除指定的单个项目（根据item_id）
            int result = examOrderMapper.deleteExamOrderItem(itemId);
            if (result <= 0) {
                return Response.error("项目删除失败");
            }

            // 4. 检查是否还有剩余项目
            int remainingItems = examOrderMapper.getOrderItemCount(orderId);

            if (remainingItems == 0) {
                // 没有剩余项目，删除整个订单和对应的收费记录
                if (deletedItem.getPayment_id() != null) {
                    paymentMapper.deletePaymentRecord(deletedItem.getPayment_id());
                }
                examOrderMapper.deleteExamOrder(orderId);
                return Response.success("检查订单已删除");
            } else {
                // 获取报销比例
                Double reimbursementRate = medicalInsuranceService.getReimbursementRate(insurance_card_number);

                // 还有剩余项目，重新计算总金额
                BigDecimal newTotal = examOrderMapper.calculateOrderTotalFee(orderId);
                examOrderMapper.updateOrderTotalFee(orderId, newTotal);
                // 计算医保支付金额
                Map<String, BigDecimal> paymentDetails = medicalInsuranceService.calculateInsurancePayment(newTotal,reimbursementRate);
                BigDecimal insurancePayment = paymentDetails.get("insurancePayment");
                BigDecimal personalPayment = paymentDetails.get("personalPayment");

                System.out.println("删除子项目更新费用"+reimbursementRate+":"+newTotal+":"+insurancePayment);

                // 更新收费记录的总金额
                if (deletedItem.getPayment_id() != null) {
                    //paymentMapper.updatePaymentAmount(deletedItem.getPayment_id(), newTotal);
                    paymentMapper.updatePaymentAmountAndInsurance(deletedItem.getPayment_id(),newTotal,insurance_card_number,reimbursementRate != null ? reimbursementRate.toString() : "0",insurancePayment,personalPayment);
                    // 删除对应的收费项目明细
                    paymentMapper.deletePaymentItemByFeeItemId(deletedItem.getPayment_id(), deletedItem.getFee_item_id());
                }
                return Response.success("检查项目删除成功");
            }
        } catch (Exception e) {
            throw new RuntimeException("删除检查项目失败：" + e.getMessage());
        }
    }

    /**
     * 更新检查申请状态
     */
    @Transactional
    public Response updateOrderStatus(ExamOrderRequest request) {
        try {
            int result = examOrderMapper.updateOrderStatus(request.getOrder_id(), request.getOrder_status());
            if (result > 0) {
                return Response.success("状态更新成功");
            } else {
                return Response.error("状态更新失败");
            }
        } catch (Exception e) {
            return Response.error("状态更新失败");
        }
    }

    /**
     * 创建收费记录
     */
    private void createPaymentRecord(ExamOrderRequest request) {
        try {
            // 获取报销比例
            Double reimbursementRate = medicalInsuranceService.getReimbursementRate(request.getInsurance_card_number());

            // 计算医保支付金额
            Map<String, BigDecimal> paymentDetails = medicalInsuranceService.calculateInsurancePayment(request.getTotal_fee(),reimbursementRate);

            BigDecimal insurancePayment = paymentDetails.get("insurancePayment");
            BigDecimal personalPayment = paymentDetails.get("personalPayment");

            // 1. 创建收费主表记录
            PaymentRecordDTO paymentRecord = new PaymentRecordDTO();
            paymentRecord.setPayment_no(generatePaymentNo());
            paymentRecord.setVisit_id(request.getVisit_id());
            paymentRecord.setPatient_name(request.getPatient_name());
            paymentRecord.setId_number(request.getId_number());
            paymentRecord.setPayment_type("examination"); // 检查费用
            paymentRecord.setSource_type("examination"); // 来源：检查单
            paymentRecord.setSource_id(request.getOrder_id()); // 关联检查订单ID
            paymentRecord.setDepartment_id(request.getDepartment_id());
            paymentRecord.setDepartment_name(request.getDepartment_name());
            paymentRecord.setPayable_amount(request.getTotal_fee());
            paymentRecord.setDiscount_amount(BigDecimal.ZERO);
            paymentRecord.setActual_amount(request.getTotal_fee());
            paymentRecord.setPaid_amount(BigDecimal.ZERO);
            paymentRecord.setPayment_status("pending"); // 待收费
            paymentRecord.setCreate_time(LocalDateTime.now());
            // 新增医保相关字段
            paymentRecord.setInsurance_card_number(request.getInsurance_card_number());
            paymentRecord.setReimbursement_rate(reimbursementRate != null ? reimbursementRate.toString() : "0");
            paymentRecord.setInsurance_payment(insurancePayment);
            paymentRecord.setPersonal_payment(personalPayment);


            int paymentResult = paymentMapper.insertPaymentRecord(paymentRecord);
            if (paymentResult <= 0) {
                throw new RuntimeException("收费记录创建失败");
            }

            Integer paymentId = paymentRecord.getPayment_id();

            // 2. 创建收费项目明细
            List<PaymentItemDTO> paymentItems = request.getOrder_items().stream()
                    .map(item -> {
                        PaymentItemDTO paymentItem = new PaymentItemDTO();
                        paymentItem.setPayment_id(paymentId);
                        paymentItem.setFee_item_id(item.getFee_item_id());
                        paymentItem.setItem_name(item.getExam_name());
                        paymentItem.setUnit_price(item.getUnit_price());
                        paymentItem.setQuantity(item.getQuantity());
                        paymentItem.setAmount(item.getAmount());
                        paymentItem.setCategory_id(getCategoryIdByExamType(item.getExam_category()));
                        paymentItem.setCategory_name(getCategoryNameByExamType(item.getExam_category()));
                        paymentItem.setInsurance_type(item.getInsurance_type());
                        paymentItem.setDoctor_id(request.getDoctor_id());
                        paymentItem.setDoctor_name(request.getDoctor_name());
                        paymentItem.setDepartment_id(request.getDepartment_id());
                        paymentItem.setDepartment_name(request.getDepartment_name());
                        paymentItem.setCreate_time(LocalDateTime.now());
                        return paymentItem;
                    })
                    .collect(Collectors.toList());

            int itemsResult = paymentMapper.insertPaymentItems(paymentItems);
            if (itemsResult <= 0) {
                System.out.println("收费项目明细创建失败");
                throw new CustomException("收费项目明细创建失败");
            }
            // 3. 更新检查项目明细的payment_id
            updateExamItemsPaymentId(request.getOrder_id(), paymentId);

        } catch (Exception e) {
            throw new CustomException("创建收费记录失败:"+e.getMessage());
        }
    }

    /**
     * 更新检查项目明细的payment_id
     */
    private void updateExamItemsPaymentId(Integer orderId, Integer paymentId) {
        try {
            // 获取该订单下的所有项目ID
            List<Integer> itemIds = examOrderMapper.selectExamItemIdsByOrderId(orderId);

            // 批量更新payment_id
            for (Integer itemId : itemIds) {
                examOrderMapper.updateExamItemPaymentId(itemId, paymentId);
            }

        } catch (Exception e) {
            throw new RuntimeException("更新检查项目支付ID失败: " + e.getMessage());
        }
    }

    /**
     * 生成收费单号
     */
    private String generatePaymentNo() {
        // 使用类似订单号的生成逻辑
        return "PAY" + System.currentTimeMillis();
    }

    /**
     * 根据检查类型获取费用类别ID
     */
    private Integer getCategoryIdByExamType(String examCategory) {
        Map<String, Integer> categoryMap = Map.of(
                "lab", 1,          // 检验检查
                "imaging", 2,      // 影像检查
                "functional", 3,   // 功能检查
                "endoscopy", 4     // 内镜检查
        );
        return categoryMap.getOrDefault(examCategory, 1);
    }

    /**
     * 根据检查类型获取费用类别名称
     */
    private String getCategoryNameByExamType(String examCategory) {
        Map<String, String> categoryNameMap = Map.of(
                "REG", "挂号费",
                "EXAM", "检查费",
                "TREAT", "治疗费",
                "MED", "药品费",
                "MAT", "材料费",
                "SURG", "手术费",
                "INP", "住院费"
        );
        return categoryNameMap.getOrDefault(examCategory, "检验检查");
    }

    /**
     * 自助缴费功能2
     * 根据有效的挂号凭证ID查询当前诊断记录相关的检查项目
     * */
    public Response getExamOrderItemListByVisit(PatientVisitDTO request){
        return Response.success(examOrderMapper.getExamOrderItemListByVisit(request.getVisit_id()));
    }

    /**
     * 自助缴费功能3
     * 进行缴费 - 这里模拟支付不涉及具体的支付金额扣除操作，只针对当前系统进行操作
     * */
    @Transactional
    public Response completeExamOrderPayment(PaymentOrderDTO request){
        // 0. 条件
        Integer paymentId = request.getPaymentId();
        Integer examOrderId = request.getExaminationOrderId();
        Integer visitId = request.getVisitId();

        // 1.1 查询当前费用信息是否存在
        PaymentVO paymentMain = paymentMapper.getPaymentMainByPaymentId(paymentId);
        if(paymentMain==null){
            return Response.error("未查询到该项费用");
        }

        // 检查是否已经支付过
        if ("completed".equals(paymentMain.getPaymentStatus())) {
            return Response.error("该费用已支付完成，无需重复支付");
        }

        // 1.2 计算医保支付和个人支付金额
        calculateInsurancePayment(paymentMain);

        // 1.3 根据payment_id更新费用表的状态和金额
        Integer updateResult = updatePaymentStatusAndAmount(paymentId, paymentMain, request.getPaymentMethod());
        if (updateResult <= 0) {
            return Response.error("更新支付状态失败");
        }

        // 2. 修改payment_item的凭证编码
        Map<Integer, String> voucherMap = updatePaymentItemVoucher(request.getPaymentId());
        if(voucherMap.isEmpty()){
            return Response.error("生成支付凭证失败");
        }

        // 3. 根据order_id修改exam_order和exam_order_item的状态
        // 3.1 更新exam_order状态逻辑
        Integer updateExamOrder = examOrderMapper.completeExamOrderPaymentByOrderId(examOrderId);
        if(updateExamOrder<=0){
            return Response.error("更新开具项目订单失败");
        }

        // 3.2 更新exam_order_item状态逻辑
        Integer updateExamItemsOrder = examOrderMapper.completeExamOrderItemsPaymentByOrderId(examOrderId);
        if(updateExamItemsOrder<=0){
            return Response.error("更新开具项目子项状态失败");
        }

        // 4. 检查项目缴费成功后返回结果对象，用于显示和打印缴费凭证
        List<PaymentItemVO> paidItems = paymentMapper.selectPaymentItemsByPaymentId(paymentId);

        // 构建返回结果
        HashMap<String,Object> result = new HashMap<>();
        result.put("paymentId",paymentId);
        result.put("paymentNo",paymentMain.getPaymentNo());
        result.put("paymentStatus", "completed");
        result.put("paymentTime", LocalDateTime.now());
        result.put("insurancePayment", paymentMain.getInsurancePayment());
        result.put("personalPayment", paymentMain.getPersonalPayment());
        result.put("paidItems", paidItems); // 包含所有item_receipt_no

        return Response.success("检查项目缴费成功", result);
    }

    /**
     * 自助缴费功能3
     * 更新支付项目凭证编码
     */
    private Map<Integer, String> updatePaymentItemVoucher(Integer paymentId) {
        // 获取支付项目列表
        List<PaymentItemVO> paymentItems = paymentMapper.selectPaymentItemsByPaymentId(paymentId);
        if (paymentItems.isEmpty()) {
            return Collections.emptyMap();
        }

        // 批量生成凭证编码
        List<String> receiptNos = PaymentItemReceiptGenerator.generateBatchItemReceiptNos(paymentItems.size());

        Map<Integer, String> voucherMap = new HashMap<>();
        for (int i = 0; i < paymentItems.size(); i++) {
            PaymentItemVO item = paymentItems.get(i);
            String receiptNo = receiptNos.get(i);

            // 更新单个项目的凭证编码
            int updateResult = paymentMapper.updatePaymentItemVoucher(item.getItem_id(), receiptNo);
            if (updateResult > 0) {
                voucherMap.put(item.getItem_id(), receiptNo);
            }
        }

        return voucherMap;
    }

    /**
     * 更新支付状态和金额
     */
    private int updatePaymentStatusAndAmount(Integer paymentId, PaymentVO payment, String paymentMethod) {
        return paymentMapper.updatePaymentAmountAndStatus(
                paymentId,
                payment.getInsurancePayment(),
                payment.getPersonalPayment(),
                "completed", // 支付状态改为已完成
                LocalDateTime.now(), // 支付时间为当前时间
                paymentMethod != null ? paymentMethod : "wechat" // 默认微信支付
        );
    }

    /**
     * 计算医保支付和个人支付金额
     */
    private void calculateInsurancePayment(PaymentVO payment) {
        // 基础金额计算：实际应收金额 = 应收金额 - 优惠金额
        BigDecimal baseAmount = payment.getPayableAmount()
                .subtract(payment.getDiscountAmount() != null ? payment.getDiscountAmount() : BigDecimal.ZERO);

        // 解析报销比例（格式如 "55.0" 表示55%）
        BigDecimal reimbursementRate = parseReimbursementRate(payment.getReimbursementRate());

        if (reimbursementRate != null && reimbursementRate.compareTo(BigDecimal.ZERO) > 0) {
            // 有医保报销的情况
            // 医保支付金额 = 基础金额 × 报销比例
            BigDecimal insurancePayment = baseAmount.multiply(reimbursementRate)
                    .setScale(2, RoundingMode.HALF_UP);

            // 个人支付金额 = 基础金额 - 医保支付金额
            BigDecimal personalPayment = baseAmount.subtract(insurancePayment)
                    .setScale(2, RoundingMode.HALF_UP);

            payment.setInsurancePayment(insurancePayment);
            payment.setPersonalPayment(personalPayment);
        } else {
            // 无医保报销的情况
            payment.setInsurancePayment(BigDecimal.ZERO);
            payment.setPersonalPayment(baseAmount);
        }
    }

    /**
     * 解析报销比例字符串
     * 支持格式："55.0" -> 0.55, "80.0" -> 0.8, "100.0" -> 1.0
     */
    private BigDecimal parseReimbursementRate(String reimbursementRateStr) {
        if (reimbursementRateStr == null || reimbursementRateStr.trim().isEmpty()) {
            return BigDecimal.ZERO;
        }

        try {
            String rateStr = reimbursementRateStr.trim();
            BigDecimal rateValue = new BigDecimal(rateStr);

            // 如果值大于1，认为是百分比格式（如55.0表示55%），需要除以100
            if (rateValue.compareTo(BigDecimal.ONE) > 0) {
                return rateValue.divide(new BigDecimal("100"), 4, RoundingMode.HALF_UP);
            } else {
                // 如果值小于等于1，直接使用
                return rateValue;
            }
        } catch (NumberFormatException e) {
            // 解析失败，返回0
            return BigDecimal.ZERO;
        }
    }
}
